package com.water_work_form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.RecordSynchronousComparison;
import com.water_work_form.mapper.BasicFormMapper;
import com.water_work_form.mapper.RecordSynchronousComparisonMapper;
import com.water_work_form.service.RecordSynchronousComparisonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录——津滨水厂同步比对原始记录 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordSynchronousComparisonServiceImpl extends ServiceImpl<RecordSynchronousComparisonMapper, RecordSynchronousComparison> implements RecordSynchronousComparisonService {

    @Autowired
    RecordSynchronousComparisonMapper recordSynchronousComparisonMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;



    /**
     * 记录——津滨水厂同步比对原始记录 项目查询（三个查询项+分页） 按照状态（status）、日期（record_date）、采样时间（sample_time）的先后顺序进行升序排序
     * @param startDate 日期（record_date）范围查询的开始日期数据，为空则不进行此项查询，否则返回record_date大于startDate的所有数据
     * @param endDate 日期（record_date）范围查询的结束日期数据，为空则不进行此项查询，否则返回record_date小于endDate的所有数据
     * @param samplingUserName 采样人姓名（sampling_user_name）列查询数据，为空则不进行此项查询，否则返回模糊查询后的所有结果
     * @param checkUserName 检测人姓名（check_user_name）列查询数据，为空则不进行此项查询，否则返回模糊查询后的所有结果
     * @param status 记录对应状态（status），为空则不进行此列查询，否则返回相应状态的所有数据
     * @param current 分页查询的当前页数
     * @param size 分页查询每页最大的数据量
     * @return 返回符合上述条件的所有数据
     */
    @Override
    public IPage<RecordSynchronousComparison> selectRecordSynchronousComparison(String startDate, String endDate, String samplingUserName, String checkUserName, String status,
                                                                                Integer current, Integer size){
        QueryWrapper<RecordSynchronousComparison> queryWrapper = new QueryWrapper<>();
        if(!startDate.isEmpty() && !endDate.isEmpty()){
            queryWrapper.ge("record_date", startDate).le("record_date", endDate);
        }
        if(!samplingUserName.isEmpty()){
            queryWrapper.like("sampling_user_name", samplingUserName);
        }
        if(!checkUserName.isEmpty()){
            queryWrapper.like("check_user_name", checkUserName);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByAsc("status", "record_date", "sampling_time");
        IPage<RecordSynchronousComparison> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 津滨水厂同步比对原始记录 查询基础表数据
     * @param name 基础表form的name列对应查询数据，返回相符合的一项，并用"form"表示
     * @return 返回查询后的数据
     */
    @Override
    public Map<String,Object> selectBasicSynchronousComparison(String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("form",basicFormMapper.getOneByName(name));
        return map;
    }

    /**
     * 记录——津滨水厂同步比对原始记录 数据表导出
     * @param recordSynchronousComparisonList 需要导出的数据表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordSynchronousComparison(List<RecordSynchronousComparison> recordSynchronousComparisonList) throws IOException {

        Map<String, Object> data = new HashMap<String, Object>();
        List<String> formatRecordDate  = new ArrayList<>();
        List<Map<String,Object>> formatList = new ArrayList<Map<String,Object>>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        formatRecordDate  = recordSynchronousComparisonList.stream()
                .map(recordSynchronousComparison -> dateFormat.format(recordSynchronousComparison.getRecordDate()))
                .collect(Collectors.toList());
        for (int i = 0;i < recordSynchronousComparisonList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("list",recordSynchronousComparisonList.get(i));
            map.put("recordDate",formatRecordDate.get(i));
            formatList.add(map);
        }
        data.put("lists",formatList);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("lists", policy).build();
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordSynchronousComparison.docx",config);
        compile.render(data);
        compile.writeToFile(destFilePath + "out_recordSynchronousComparison.docx");
        compile.close();
    }


}
